package com.study.base.io.nio.mainsubreactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by tan on 2017/7/14.
 */
public class Handler implements Runnable {
	private SocketChannel socket;
	private SelectionKey key;
	static final int READING = 0, SENDING = 0;
	int state = READING;

	private ByteBuffer input = ByteBuffer.allocate(8 * 1000);
	private ByteBuffer output = ByteBuffer.allocate(8 * 1000);

	public Handler(Selector selector, SocketChannel socket) throws IOException {
		this.socket = socket;
		this.socket.configureBlocking(false);
		key = socket.register(selector, 0);
		key.attach(this);

		key.interestOps(SelectionKey.OP_READ);
		selector.wakeup();
	}

	@Override
	public void run() {
		try {
			if (state == READING)
				read();
			else if (state == SENDING)
				send();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void read() throws IOException {
		socket.read(input);
		if (inputIsComplete()) {
			process();
			state = SENDING;
			key.interestOps(SelectionKey.OP_WRITE);
		}
	}

	private void send() throws IOException {
		socket.write(output);
		if (outputIsComplete()) {
			key.cancel();
		}
	}


	private boolean inputIsComplete() {
		return true;
	}

	private boolean outputIsComplete() {
		return true;
	}

	void process() {
		System.out.println("process");
	}
}
